package com.talkyoung.ptbpro.controller;

import com.talkyoung.ptbcommon.CommonResult;
import com.talkyoung.ptbpro.common.util.AliyunOSSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
public class UploadController {

    private static Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    AliyunOSSUtil aliyunOSSUtil;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public CommonResult<String> upload(@RequestParam(name = "profilePhoto") MultipartFile multipartFile, HttpServletRequest request){
        //获取文件在服务器的储存位置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        logger.debug("文件的保存路径：" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            logger.debug("目录不存在，创建目录:" + filePath);
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = multipartFile.getOriginalFilename();
        logger.debug("原始文件名称：" + originalFileName);

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        logger.debug("文件类型：" + type);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        try {
            String url = aliyunOSSUtil.uploadSingleFile(multipartFile,type);
            logger.debug("upload success");
            return CommonResult.success(url);
        }catch (Exception e){
            logger.error("upload failed：",e);
            return CommonResult.failed("上传失败");
        }
    }
}
